import { useMemoizedFn } from 'ahooks';
import { useEffect } from 'react';

export function useTimerSimple(fn: () => void, delay: number = 1000) {
  useEffect(() => {
    const timer = setInterval(fn, delay);
    return () => clearInterval(timer);
  }, [delay]);
}

export function useTimer(fn: () => void, delay: number = 1000) {
  // const fnRef = useRef<(() => void)>(fn); // 缓存回调函数
  // fnRef.current = useMemo(() => fn, [fn]);
  // const timerCallback = () => {
  //   fnRef.current?.();
  // };

  const timerCallback = useMemoizedFn(fn); // 缓存回调函数
  useEffect(() => {
    console.log('执行useTimer', fn);
    const timer = setInterval(timerCallback, delay);
    return () => clearInterval(timer);
  }, [delay]);
}
